package com.campus.food.controller;

import com.campus.food.exception.BusinessException;
import com.campus.food.model.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传控制器
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-06-12
 */
@RestController
@RequestMapping("/api/upload")
public class FileController {

    @Value("${file.upload.path:/uploads}")
    private String uploadPath;
    
    @Value("${file.access.path:/uploads}")
    private String accessPath;
    
    /**
     * 上传图片
     * 
     * @param file 图片文件
     * @return 图片访问路径
     */
    @PostMapping(value = "/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException("上传的文件不能为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new BusinessException("只能上传图片文件");
        }
        
        // 生成文件保存路径
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String directory = uploadPath + "/images/" + datePath;
        
        // 创建目录
        File dir = new File(directory);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new BusinessException("创建目录失败");
            }
        }
        
        // 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        
        // 保存文件
        try {
            File dest = new File(directory + "/" + filename);
            file.transferTo(dest);
            
            // 返回可访问的URL
            String fileUrl = accessPath + "/images/" + datePath + "/" + filename;
            return Result.success(fileUrl);
        } catch (IOException e) {
            throw new BusinessException("上传文件失败: " + e.getMessage());
        }
    }
} 